package org.iteam.web.struts.interceptor;

import org.iteam.web.shiro.ShiroUtil;
import org.iteam.web.struts.action.JsonAction;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class CustomInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	boolean state = true;

	@SuppressWarnings("unchecked")
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// System.out.println("当前用户是否验证:" + ShiroUtil.isAuthenticated());
		System.out.println("验证用户登录状态");
		if (!ShiroUtil.isAuthenticated()) {
			System.out.println("[用户登录失效1]");
			// 如果是调用ajax方法进行返回map的处理
			if (invocation.getProxy().getMethod().equalsIgnoreCase("query")
					|| invocation.getProxy().getMethod()
							.equalsIgnoreCase("create")
					|| invocation.getProxy().getMethod()
							.equalsIgnoreCase("update")
					|| invocation.getProxy().getMethod()
							.equalsIgnoreCase("delete")
					|| invocation.getProxy().getMethod()
							.equalsIgnoreCase("destroy")) {
				JsonAction action = (JsonAction) invocation.getAction();
				invocation.getStack().setValue("state", false);
				action.getMap().put("state", false);
				state = false;
				action.getMap().put("info", "用户帐号登录已过期，请重新登录!");
				return "MAP";
			} else {
				if (!invocation.getAction().getClass().getSimpleName()
						.equalsIgnoreCase("LoginAction"))
					throw new Exception("用户帐号登录已过期，请重新登录!!");
				// invocation.setResultCode("unknownError");
			}
		}

		// invocation.addPreResultListener(new PreResultListener() {
		// public void beforeResult(ActionInvocation invocation,
		// String resultCode) {
		// System.out.println("state:"+state);
		// if (!state) {
		// System.out.println("[用户登录失效2]");
		// invocation.getStack().setValue("state", false);
		// JsonAction action = (JsonAction) invocation.getAction();
		// action.getMap().put("state", false);
		// action.getMap().put("info", "用户帐号登录已过期，请重新登录!!!");
		// }
		// }
		//
		// });
		return invocation.invoke();
	}
}
